#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年9月25日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

'''
    在docker 容器中 批量设置 hosts
'''

import paramiko





def get_hostname(ip='localhost',port=22):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,"root", "zhimatech")
    
    stdin , stdout , stderr = ssh.exec_command('hostname')
    hostname =  stdout.read() 
    return hostname.strip()


def write_hosts(ip='localhost',port=22,hosts=[]):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,"root", "zhimatech")
    for host_str in hosts:
        print 'cat "%s" >> %s'%(host_str,'/etc/hosts')
        stdin , stdout , stderr = ssh.exec_command('echo "%s" >> %s'%(host_str,'/etc/hosts'))
        print stdout.read()

def change_hosts(ips=[],OtherHosts=[]):
    hosts = []
    for ip_and_port in ips:
        ip,port = ip_and_port.split(':')
        hostname = get_hostname(ip=ip,port=int(port))
        nip = get_ip(ip=ip,port=int(port))
        hosts.append( "%s    %s"%(nip,hostname))
        
    print '\n'.join(hosts)
        
    for ip_and_port in ips:
        ip,port = ip_and_port.split(':')
        hostname = get_hostname(ip=ip,port=int(port))
        write_hosts(ip=ip,port=int(port),hosts=hosts+OtherHosts)



def get_localip_and_hostname(ips=[]):
    hosts = []
    for ip_and_port in ips:
        ip,port = ip_and_port.split(':')
        hostname = get_hostname(ip=ip,port=int(port))
        nip = get_ip(ip=ip,port=int(port))
        hosts.append( "%s    %s"%(nip,hostname))
    return hosts

def get_ip(ip='localhost',port=22):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,int(port),"root", "zhimatech")
    
    stdin , stdout , stderr = ssh.exec_command("ifconfig eth0 | grep 'inet addr' | awk '{ print $2}' | awk -F: '{print $2}'")
    ip =  stdout.read() 
    return ip.strip()

#get_hosts(ips=["192.168.1.201"])

ips = ['192.168.1.208:10122',
       '192.168.1.208:10222',
       '192.168.1.208:10322',
       '192.168.1.208:10422',
       '192.168.1.208:10522',
       '192.168.1.208:10622',
       '192.168.1.208:10722',
       '192.168.1.208:10822'
       ]

#kafka
kafka_ips = [
             '192.168.1.208:12022',
             '192.168.1.208:12122',
             '192.168.1.208:12222',
             '192.168.1.208:12322'
             ]

#hadoop
hadoop_ips = [
       '192.168.1.208:11022',
       '192.168.1.208:11122',
       '192.168.1.208:11222',
       '192.168.1.208:11322'
       ]


KafkaHosts = get_localip_and_hostname(kafka_ips)
HadoopHosts = get_localip_and_hostname(hadoop_ips)

group_ips = [
             '192.168.1.208:13022',
             '192.168.1.208:13122'
             ]

change_hosts(group_ips,KafkaHosts+HadoopHosts)


